package samplebasic

import sweet.mvc.api._
import sweet.helper._
import java.io._
import java.util.jar.Manifest

class AdminController(props: scala.collection.Map[String,String], ctxPath: String) extends FormController {
  handleReq("/sysinfo"){ req => 
    HandlerNameView(
      "sysprops" -> formattedSysProps,
      "appprops" -> props
    )
  }
  
  handle("/index"){ HandlerNameView() }
    
  /** Replace all sep with space so htnl view can display multi lines.*/
  lazy val formattedSysProps = {
    val sep = java.io.File.pathSeparator
    val props = JSystem.props
    for((k,v) <- props)
      if(k.contains("path"))
        props(k) = v.replaceAll(sep, sep+" ")
    props    
  }
  
  val adminLoginForm = new Form("adminLogin"){
    addField("password", "Admin Password", StringConverter){
      VRequired() ++ VLen(3, 32, "Length must between 3 to 32 characters") ++
      VValue("Password not match"){ v=> v == props("adminPassword") }
    }
  }
  
  handleForm("/login", adminLoginForm){ 
    new FormHandler(){
      def viewForm(formData: FormData, req: Req) =  HandlerNameView()
      def processForm(formData: FormData, req: Req) = {
        req.sess("adminLogin") = true
        View("redirect:/index")
      }
    }
  }
  
  handleReq("/logout"){ req =>
    req.sess.remove("adminLogin")
    View("redirect:/login")
  }
}
